package edu.colorado.karl.mainsched;

/**
 * Starts the threads that run the back-end of the system.  The DataManager
 * is the class which is invoked to start the program.  It will then spawn
 * two threads to attend to the Intelligent Scheduler and Database Management
 * modules.
 * @author Andrew Boehm and Michael Knudson
 * @version 5/4/08
 */
public class DataManager {
	private static DataManager dm = null;
	private static DatabaseThread dt = null;
	private static SchedulerThread sp = null;
	
	/**
	 * Returns an instance of a DataManager.  There is only one 
	 * DataManager instance in the program at a time.
	 * @return an instance of a DataManager.
	 */
	public static DataManager getInstance() {
		if(dm == null)
			dm = new DataManager();
		return dm;
	}
	
	/**
	 * The main method to invoke when starting the program.
	 * @param args	Command-line arguments
	 */
	public static void main(String[] args) {
		DataManager d = DataManager.getInstance();
		d.run();
	}
	
	private DataManager() {
		// separate thread invokes scheduler every hour
		sp = new SchedulerThread();
		// separate thread stores trend data every 5 min
		dt = new DatabaseThread();
	}

	//	Starts up all the appropriate stuff
	private void init() {
		dt.start();	// Runs the database module
		sp.start();	// Runs the scheduler
	}

	/**
	 * Runs the IntelliCORE system.
	 */
	public void run() {
		init();
//		while(true) {
			try {
				// Insert some really big number to keep the program running
				// Eventually this thread will be daemonized, making this unncessary
				Thread.sleep(100000);
			} catch (InterruptedException e) {
//				break;
			}
//		}
		sp.interrupt();
		dt.interrupt();
		
		try {
			sp.join();
			dt.join();
		} catch (InterruptedException e) {
//			e.printStackTrace();
		}
	}
}
